package org.jeecg.modules.company.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.hibernate.validator.internal.util.StringHelper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.company.dto.ComAdminUserDto;
import org.jeecg.modules.company.entity.ComInfo;
import org.jeecg.modules.company.service.IComAdminUserService;
import org.jeecg.modules.company.service.IComInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 企业基本信息表
 * @Author: jeecg-boot
 * @Date:   2020-03-15
 * @Version: V1.0
 */
@Api(tags="企业基本信息表")
@RestController
@RequestMapping("/company/comInfo")
@Slf4j
public class ComInfoController extends JeecgController<ComInfo, IComInfoService> {
	@Autowired
	private IComInfoService comInfoService;
	@Autowired
	private IComAdminUserService comAdminUserService;
	/**
	 * 分页列表查询
	 *
	 * @param comInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "企业基本信息表-分页列表查询")
	@ApiOperation(value="企业基本信息表-分页列表查询", notes="企业基本信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ComInfo comInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ComInfo> queryWrapper = QueryGenerator.initQueryWrapper(comInfo, req.getParameterMap());
		Page<ComInfo> page = new Page<ComInfo>(pageNo, pageSize);
		IPage<ComInfo> pageList = comInfoService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param comInfo
	 * @return
	 */
	@AutoLog(value = "企业基本信息表-添加或更新")
	@ApiOperation(value="企业基本信息表-添加或更新", notes="企业基本信息表-添加或更新")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ComInfo comInfo,HttpServletRequest request) {
		String token = request.getHeader("X-Access-Token");
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("查看失败，用户不存在！");
		}
		String username = JwtUtil.getUsername(token);
		//判断是否该用户已创建企业信息，如果存在，则执行更新操作
		String id=comInfoService.getByUserName(username);
		if(StringHelper.isNullOrEmptyString(id)){
			comInfoService.save(comInfo);
		}else{
			comInfo.setId(id);
			comInfoService.updateById(comInfo);
		}
		return Result.ok("操作成功！");
	}

	/**
	 *  编辑
	 *
	 * @param comInfo
	 * @return
	 */
	@AutoLog(value = "企业基本信息表-编辑")
	@ApiOperation(value="企业基本信息表-编辑", notes="企业基本信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ComInfo comInfo) {
		comInfoService.updateById(comInfo);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业基本信息表-通过id删除")
	@ApiOperation(value="企业基本信息表-通过id删除", notes="企业基本信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		comInfoService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业基本信息表-批量删除")
	@ApiOperation(value="企业基本信息表-批量删除", notes="企业基本信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.comInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业基本信息表-通过id查询")
	@ApiOperation(value="企业基本信息表-通过id查询", notes="企业基本信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		JSONObject comInfo = comInfoService.getComInfoById(id);
		if(comInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(comInfo);
	}
	 /**
	  * 通过用户查看
	  *
	  * @return
	  */
	 @AutoLog(value = "详情查看")
	 @ApiOperation(value="详情-通过id查询", notes="详情查看")
	 @GetMapping(value = "/getComDetail")
	public Result<?> getComDetail(HttpServletRequest request){
		String token = request.getHeader("X-Access-Token");
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("查看失败，用户不存在！");
		}
		String username = JwtUtil.getUsername(token);
		//查询企业基本信息id
		 String  id  = comInfoService.getByUserName(username);
		 JSONObject comInfo = comInfoService.getComInfoById(id);
		 if(comInfo==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.ok(comInfo);
	}




    /**
    * 导出excel
    *
    * @param request
    * @param comInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ComInfo comInfo) {
        return super.exportXls(request, comInfo, ComInfo.class, "企业基本信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            //params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ComInfo> comInfos = ExcelImportUtil.importExcel(file.getInputStream(), ComInfo.class, params);
                //comInfoService.saveBatch(comInfos);
                for (ComInfo comInfo : comInfos) {
                	String  id = UUID.randomUUID().toString().replaceAll("-","");
                	comInfo.setId(id);//企业信息主键id
                	comInfoService.save(comInfo);
                	//TODO:保存企业用户登录账号（同时保存与企业的关联关系和角色关系）
                	ComAdminUserDto dto = new ComAdminUserDto();
                	dto.setCompanyId(id);
                	dto.setRealname(comInfo.getCompanyName());
                    comAdminUserService.saveCompanyAdminUser(dto);
                }
                return Result.ok("文件导入成功！数据行数：" + comInfos.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败.");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                	log.error(e.getMessage(), e);
                }
            }
        }
        return Result.error("文件导入失败！");
       // return super.importExcel(request, response, ComInfo.class);
    }
	 /**
	  * 企业用户查询
	  * @param request
	  * @param response
	  * @return
	  */
	 @SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	@AutoLog(value = "企业用户查询")
	 @ApiOperation(value="企业用户查询", notes="企业用户查询")
	 @RequestMapping(value = "/getComUser")
	 public Result<?> getComUser(HttpServletRequest request,
								 HttpServletResponse response,
								 @RequestParam(name="company_name",required=false) String company_name,
								 @RequestParam(name="company_type",required=false) String industry,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize
								 ) {
	 	JSONObject resultObject=new JSONObject();
	 	Map paramMap=new HashMap();
		 paramMap.put("company_name",company_name);
		 paramMap.put("industry",industry);
		 paramMap.put("pageNo",pageNo);
		 paramMap.put("pageSize",pageSize);
		 IPage<Map> result  = comInfoService.getComUser(paramMap);
		 return Result.ok(result);
	 }

	 /**
	  * 启用
	  * @param request
	  * @param response
	  * @return
	  */
	 @SuppressWarnings({ "rawtypes", "unchecked" })
	@AutoLog(value = "启用企业用户")
	 @ApiOperation(value="启用企业用户", notes="启用企业用户")
	 @RequestMapping(value = "/startCom")
	 public Result<?> startCom(HttpServletRequest request, HttpServletResponse response,@RequestParam(name="id",required=true) String id) {
		 JSONObject resultObject=new JSONObject();
		 Map paramMap=new HashMap();
		 paramMap.put("id",id);
		 resultObject  = comInfoService.startCom(paramMap);
		 return Result.ok(resultObject);
	 }
	 /**
	  * 停用
	  * @param request
	  * @param response
	  * @return
	  */
	 @SuppressWarnings({ "rawtypes", "unchecked" })
	@AutoLog(value = "停用企业用户")
	 @ApiOperation(value="停用企业用户", notes="停用企业用户")
	 @RequestMapping(value = "/stopCom")
	 public Result<?> stopCom(HttpServletRequest request, HttpServletResponse response,@RequestParam(name="id",required=true) String id) {
		 JSONObject resultObject=new JSONObject();
		 Map paramMap=new HashMap();
		 paramMap.put("id",id);
		 resultObject  = comInfoService.stopCom(paramMap);
		 return Result.ok(resultObject);
	 }

	 /**
	  *查询企业列表
	  * @return
	  */
	 @AutoLog(value = "获取企业列表")
	 @ApiOperation(value="获取企业列表", notes="获取企业列表")
	 @RequestMapping(value = "/getComName")
	 public Result<?> getComName() {
		 JSONObject resultObject=new JSONObject();
		 resultObject  = comInfoService.getComName();
		 return Result.ok(resultObject);
	 }

}
